

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/boshi.jpeg">
  <link rel="icon" type="image/png" href="/img/boshi.jpeg">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="wangpf">
  <meta name="keywords" content="">
  <title>手写DOM - wpf的博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/foundation.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_6peoq002giu.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.1.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>Wangpf's blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/article.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-12-06 20:09" pubdate>
      2020年12月6日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.4k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      33
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">手写DOM</h1>
            
            <div class="markdown-body" id="post-body">
              <h1 id="手写DOM库"><a href="#手写DOM库" class="headerlink" title="手写DOM库"></a>手写DOM库</h1><p>因为DOM原生API太难用了<br><a target="_blank" rel="noopener" href="https://github.com/wwwpppfffzzz/DOM-Library/blob/master/src/dom.js">源代码链接</a></p>
<h2 id="对象风格"><a href="#对象风格" class="headerlink" title="对象风格"></a>对象风格</h2><ul>
<li>window.dom  是我们提供的全局对象</li>
</ul>
<h2 id="增加节点"><a href="#增加节点" class="headerlink" title="增加节点"></a>增加节点</h2><ul>
<li><div class="hljs"><pre><code class="js">dom.append(parent,child)  // 用于新增儿子节点
<pre><code class="hljs autohotkey">
- ```js
  dom.wrap(`&lt;div&gt;&lt;/div&gt;`)   // 用于新增爸爸节点</code></pre></div>


</code></pre>
</li>
</ul>
<h3 id="dom-create-函数"><a href="#dom-create-函数" class="headerlink" title="dom.create 函数"></a>dom.create 函数</h3><div class="hljs"><pre><code class="hljs js">dom.create(<span class="hljs-string">`&lt;div&gt;&lt;span&gt;hi&lt;/span&gt;&lt;/div&gt;`</span>) <span class="hljs-comment">// 用于创建节点</span></code></pre></div>

<ul>
<li>一般我们创造节点的目的就是在别的节点中插入此节点，</li>
<li>那么我要封装一个 以输入 <code>html格式的</code>  的 create函数</li>
<li>能够在创造节点的同时在里面加一些其他节点</li>
<li>传入的字符串要是以有标签的 以html的形式来</li>
</ul>
<p><strong>dom.create源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">create(string) &#123;
    <span class="hljs-comment">// 创建容器    template标签可以容纳任意元素</span>
    <span class="hljs-keyword">const</span> container = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">&#x27;template&#x27;</span>)
    <span class="hljs-comment">// 要trim，防止拿到空字符</span>
    container.innerHTML = string.trim()
    <span class="hljs-comment">// 必须要 使用 .content  要不然拿不到</span>
    <span class="hljs-keyword">return</span> container.content.firstChild

    <span class="hljs-comment">// 或者</span>
    <span class="hljs-comment">// container.innerHTML = string</span>
    <span class="hljs-comment">// return container.content.children[0]</span>
  &#125;</code></pre></div>



<p><strong>示例</strong></p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> div = dom.create(<span class="hljs-string">&#x27;&lt;div&gt;&lt;span&gt;hello&lt;/span&gt;&lt;/div&gt;&#x27;</span>)
<span class="hljs-built_in">console</span>.log(div);</code></pre></div>

<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/36537b52b1f34ae8a5b6fcbc0ef2b6c4~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif"></p>
<h3 id="dom-after-函数"><a href="#dom-after-函数" class="headerlink" title="dom.after 函数"></a>dom.after 函数</h3><blockquote>
<p> 由于dom中的api由于只有添加前面的节点的方法，如果想要往某个节点的后面插入节点非常的费劲</p>
</blockquote>
<div class="hljs"><pre><code class="hljs js">dom.after(node,newNode)     <span class="hljs-comment">// 用于新增下一个（弟弟）节点</span></code></pre></div>



<p><strong>dom.after  源代码</strong></p>
<blockquote>
<p>这里不比担心 如果 node 这个节点是最后一个节点怎么办。   即使为null，依然能插入的 </p>
</blockquote>
<div class="hljs"><pre><code class="hljs js">after(node, newNode) &#123;
   <span class="hljs-comment">// 找到此节点的爸爸然后调用insertBefore（插入某个节点的前面）方法，</span>
   <span class="hljs-comment">//把 newNode 插入到下一个节点的前面</span>
   <span class="hljs-keyword">return</span> node.parentNode.insertBefore(newNode, node.nextSibling)
 &#125;</code></pre></div>

<p><strong>示例</strong><br><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fa16a738b5f34d46966261afd6b3dace~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif"></p>
<h3 id="dom-before-函数"><a href="#dom-before-函数" class="headerlink" title="dom.before 函数"></a>dom.before 函数</h3><blockquote>
<p>这个方法和 dom.after 方法思路一致，</p>
</blockquote>
<div class="hljs"><pre><code class="hljs js">dom.before(node,node2)   <span class="hljs-comment">// 用于新增上一个(哥哥)节点</span></code></pre></div>


<p><strong>dom.before 源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">before(node, newNode) &#123;
    <span class="hljs-comment">// 正常的返回DOM原生的添加前面的节点的方法即可</span>
    <span class="hljs-keyword">return</span> node.parentNode.insertBefore(newNode, Node)
  &#125;</code></pre></div>

<h3 id="dom-append-函数"><a href="#dom-append-函数" class="headerlink" title="dom.append 函数"></a>dom.append 函数</h3><div class="hljs"><pre><code class="hljs js">dom.append(parent,child)  <span class="hljs-comment">// 用于新增儿子节点</span></code></pre></div>



<p><strong>dom.append 源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">append(parent, node) &#123;
  <span class="hljs-keyword">return</span> parent.appendChild(node)
&#125;</code></pre></div>

<h3 id="dom-wrap函数"><a href="#dom-wrap函数" class="headerlink" title="dom.wrap函数"></a>dom.wrap函数</h3><blockquote>
<p>实现思路:     先把这个节点先从DOM树中移出来，把原来的位置插入新的(爸爸)节点，然后在这个爸爸节点中插入原来的节点</p>
</blockquote>
<div class="hljs"><pre><code class="hljs js">dom.wrap(<span class="hljs-string">`&lt;div&gt;&lt;/div&gt;`</span>)   <span class="hljs-comment">// 用于添加在此节点外面套一个节点   (爸爸)节点</span></code></pre></div>



<p><strong>dom.wrap 源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">wrap(node, newNode) &#123;
  <span class="hljs-comment">// 先把newNode放在node节点的前面   后面也行</span>
  dom.before(node, newNode)
  <span class="hljs-comment">// 然后把node节点放在newNode里面</span>
  dom.append(newNode, node)
&#125;</code></pre></div>



<p><strong>实现思路图：</strong><br><img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/60febc04d6834004ab09609d6786a3be~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="dom.wrap思路图"></p>
<p><strong>示例：</strong><br><img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/13007f4503b94595869b700d5781008a~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="示例"></p>
<h2 id="删除节点"><a href="#删除节点" class="headerlink" title="删除节点"></a>删除节点</h2><ul>
<li><div class="hljs"><pre><code class="js">dom.remove(node) // 用于删除节点
<pre><code class="hljs php">
- ```js
  dom.<span class="hljs-keyword">empty</span>(<span class="hljs-built_in">parent</span>)  <span class="hljs-comment">// 用于删除后代</span></code></pre></div>


</code></pre>
</li>
</ul>
<h3 id="dom-remove-函数"><a href="#dom-remove-函数" class="headerlink" title="dom.remove 函数"></a>dom.remove 函数</h3><blockquote>
<p>用法： 删除某一个节点，并返回这个节点</p>
<p>思路 ： 让他的爸爸删除他的儿子。  </p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">remove(node) &#123;
  node.parentNode.removeChild(node)
  <span class="hljs-comment">//返回删除的节点</span>
  <span class="hljs-keyword">return</span> node
 &#125;</code></pre></div>





<h3 id="dom-empty-函数"><a href="#dom-empty-函数" class="headerlink" title="dom.empty 函数"></a>dom.empty 函数</h3><blockquote>
<p>用法： 删除这个节点的所有子代</p>
<p>思路:   遍历删除它的所有子节点，并返回 删除的节点</p>
</blockquote>
<blockquote>
<p>不能用for循环的原因：因为每次 dom.remove 删除的时候，它的长度就会随之改变， 而我们又在for循环它，因此我测试时候会出现bug，因此我们选择使用 while 循环 解决。</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">empty(node) &#123;
  <span class="hljs-keyword">const</span> firstChild = node.firstChild
  <span class="hljs-keyword">while</span> (firstChild) &#123; 
    array.push(dom.remove(node.firstChild))
  &#125;
  <span class="hljs-comment">// 返回删除的节点</span>
  <span class="hljs-keyword">return</span> array
&#125;</code></pre></div>

<p><strong>示例</strong></p>
<p><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/018c6fbad15345c5bfb5a666d0f224ee~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="删除节点"></p>
<h2 id="修改"><a href="#修改" class="headerlink" title="修改"></a>修改</h2><ul>
<li><div class="hljs"><pre><code class="js">dom.attr(node,&#39;title&#39;,&#39;hello&#39;)  //将node节点中的 title 属性值改为 hello    用于读写属性,,
dom.attr(node,&#39;title&#39;)  // 获取 node节点的title属性值
<pre><code class="hljs crmsh">
- ```js
  dom.text(<span class="hljs-keyword">node</span><span class="hljs-title">,&#x27;我是修改后的&#x27;)  //将node</span>节点中的文本修改为xxxxx    用于读写文本内容
  dom.text(<span class="hljs-keyword">node</span><span class="hljs-title">)   // 查看文本内容</span></code></pre></div></code></pre>
</li>
<li><div class="hljs"><pre><code class="js">dom.html(node,&#39;&lt;em&gt;我是修改后的&lt;/em&gt;&#39;)  //将node节点中的html元素内容修改为xxxx ,  用于读写html内容
dom.html(node)  // 查看此节点中的html内容
<pre><code class="hljs crmsh">
- ```js
  dom.style(<span class="hljs-keyword">node</span><span class="hljs-title">,&#123;color</span>:&#x27;red&#x27;&#125;)   // 用于修改style样式</code></pre></div></code></pre>
</li>
<li><div class="hljs"><pre><code class="js">dom.class.add(node,&#39;btn&#39;)  // 用于添加class类名
<pre><code class="hljs crmsh">
- ```js
  dom.class.remove(<span class="hljs-keyword">node</span><span class="hljs-title">,&#x27;btn</span>&#x27;)   // 用于删除class</code></pre></div></code></pre>
</li>
<li><div class="hljs"><pre><code class="js">dom.class.has(node,&#39;btn&#39;)  // 查看是否拥有类名
<pre><code class="hljs crmsh">
- ```js
  dom.on(<span class="hljs-keyword">node</span><span class="hljs-title">,&#x27;click</span>&#x27;,fn) // 用于添加事件监听</code></pre></div></code></pre>
</li>
<li><div class="hljs"><pre><code class="js">dom.off(node,&#39;click&#39;,fn)  // 用于删除事件监听
<pre><code class="hljs">




### dom.attr 函数

&gt; 用法： 如果传入的是三个参数     设置/修改 该节点中的属性值和属性名 
&gt;
&gt; ```js
&gt; dom.attr(node,&#x27;title&#x27;,&#x27;hello&#x27;)		// 传入三个参数，就设置它的属性名和属性值
&gt; dom.attr(node,&#x27;title&#x27;)    // 如果传入的是俩个参数    获取属性名</code></pre></div>
</code></pre>
</li>
</ul>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">attr(node, name, value) &#123;
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">arguments</span>.length === <span class="hljs-number">3</span>) &#123;
    <span class="hljs-comment">// 设置该节点某个属性和属性值</span>
    node.setAttribute(name, value)
  &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-built_in">arguments</span>.length === <span class="hljs-number">2</span>) &#123;
    <span class="hljs-comment">// 查看该节点某个属性的值</span>
    <span class="hljs-keyword">return</span> node.getAttribute(name)
  &#125;
&#125;</code></pre></div>



<p><strong>示例</strong></p>
<p><img src="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/09d6fb8575c04d98bed9e14938761a80~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="示例"><br><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d4e548da4e5c4ad9ba7180914f9c3892~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="示例"></p>
<h3 id="dom-text-函数"><a href="#dom-text-函数" class="headerlink" title="dom.text 函数"></a>dom.text 函数</h3><blockquote>
<p>用法  和 <code>innerText </code>一致</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">text(node, string) &#123;
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">arguments</span>.length === <span class="hljs-number">2</span>) &#123;   <span class="hljs-comment">// 重载</span>
    <span class="hljs-keyword">if</span> (<span class="hljs-string">&#x27;innerText&#x27;</span> <span class="hljs-keyword">in</span> node) &#123;  <span class="hljs-comment">// 适配 </span>
      node.innerText = string
    &#125; <span class="hljs-keyword">else</span> &#123;
      node.textContent = string
    &#125;
  &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-built_in">arguments</span>.length === <span class="hljs-number">1</span>) &#123;
    <span class="hljs-keyword">if</span> (<span class="hljs-string">&#x27;innerText&#x27;</span> <span class="hljs-keyword">in</span> node) &#123;
      <span class="hljs-keyword">return</span> node.innerText
    &#125; <span class="hljs-keyword">else</span> &#123;
      <span class="hljs-keyword">return</span> node.textContent
    &#125;
  &#125;
&#125;</code></pre></div>



<p><strong>示例</strong></p>
<p><img src="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/52ce828d8a844f4e96acb44e565a8f87~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="dom.text示例"></p>
<h3 id="dom-html-函数"><a href="#dom-html-函数" class="headerlink" title="dom.html 函数"></a>dom.html 函数</h3><blockquote>
<p>用法和 innerHTML 一致</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">html(node, string) &#123;
   <span class="hljs-keyword">if</span> (<span class="hljs-built_in">arguments</span>.length === <span class="hljs-number">2</span>) &#123;
     node.innerHTML = string
   &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-built_in">arguments</span>.length === <span class="hljs-number">1</span>) &#123;
     <span class="hljs-keyword">return</span> node.innerHTML
   &#125;
 &#125;</code></pre></div>







<h3 id="dom-style-函数"><a href="#dom-style-函数" class="headerlink" title="dom.style 函数"></a>dom.style 函数</h3><blockquote>
<p>原生DOM操作style的写法是： </p>
<div class="hljs"><pre><code class="hljs js">xxx.style.color = <span class="hljs-string">&#x27;red&#x27;</span>  或者  xxx.style[<span class="hljs-string">&#x27;color&#x27;</span>]  = <span class="hljs-string">&#x27;red&#x27;</span></code></pre></div>

<p>我封装的修饰style 的写法：</p>
<div class="hljs"><pre><code class="hljs js">dom.style(xxx,<span class="hljs-string">&#x27;color&#x27;</span>,<span class="hljs-string">&#x27;red&#x27;</span>)		<span class="hljs-comment">// 使用字符串的形式 来修改样式</span>
dom.style(xxx,&#123;<span class="hljs-attr">color</span>:<span class="hljs-string">&#x27;red&#x27;</span>&#125;)        <span class="hljs-comment">// 使用对象的形式   来修改样式</span>

dom.style(xxx,<span class="hljs-string">&#x27;color&#x27;</span>)    <span class="hljs-comment">// 查看样式的内容</span></code></pre></div>
</blockquote>
<blockquote>
<p>思路: 我们可以引用原生的第二种写法 ，遍历属性值key‘，用xxx.style[key]实现  ， 此时的color 是一个变量需要从我们传入的对象中获取。 为什么不用  style.color=’red’ 的原因是因为 对象的属性值是字符串。</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">style(node, name, value) &#123;
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">arguments</span>.length === <span class="hljs-number">3</span>) &#123;
      <span class="hljs-comment">// dom.style(xxx,&#x27;color&#x27;,&#x27;red&#x27;)</span>
    node.style[name] = value
  &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-built_in">arguments</span>.length === <span class="hljs-number">2</span>) &#123;
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> name === <span class="hljs-string">&#x27;string&#x27;</span>) &#123;
      <span class="hljs-comment">// dom.style(xxx,&#x27;color&#x27;)</span>
      <span class="hljs-keyword">return</span> node.style[name]
    &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (name <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Object</span>) &#123;
      <span class="hljs-comment">// dom.style(xxx,&#123;color:&#x27;red&#x27;&#125;)</span>
      <span class="hljs-keyword">const</span> object = name
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> object) &#123;
        <span class="hljs-comment">// 不能用 style.key 是因为 key是变量</span>
        node.style[key] = object[key]
      &#125;
    &#125;
  &#125;
&#125;</code></pre></div>



<p><strong>示例</strong></p>
<p><strong>使用对象的形式来修改样式：</strong><br><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f2c571b3928e40159429a2bec14f2db4~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="示例1"></p>
<p><strong>使字符串的形式来修改样式</strong></p>
<img src="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0e2cc02b488642babab86bccdf505df1~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="示例2"  />







<h3 id="dom-class-函数"><a href="#dom-class-函数" class="headerlink" title="dom.class 函数"></a>dom.class 函数</h3><blockquote>
<p>用法：</p>
<div class="hljs"><pre><code class="hljs js">dom.class.add(test, <span class="hljs-string">&#x27;red&#x27;</span>)   <span class="hljs-comment">// 添加类名</span>
dom.class.remove(test, <span class="hljs-string">&#x27;red&#x27;</span>)   <span class="hljs-comment">//  删除类名</span>
<span class="hljs-built_in">console</span>.log(dom.class.has(test, <span class="hljs-string">&#x27;red&#x27;</span>));   <span class="hljs-comment">// 查看类名</span></code></pre></div>
</blockquote>
<blockquote>
<p>思路：首先在class 对象中 创建三个不同功能的方法。 然后封装一下原生的DOM即可。</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">class: &#123;
  add(node, className) &#123;
    node.classList.add(className)
  &#125;,
  remove(node, className) &#123;
    node.classList.remove(className)
  &#125;,
  has(node, className) &#123;
    <span class="hljs-keyword">return</span> node.classList.contains(className)
  &#125;
&#125;</code></pre></div>



<p><strong>示例</strong></p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/270cf57e749d4750bc25cee4c5e3e17f~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="示例1"></p>
<h3 id="dom-on-函数-和-dom-off-函数"><a href="#dom-on-函数-和-dom-off-函数" class="headerlink" title="dom.on 函数 和  dom.off 函数"></a>dom.on 函数 和  dom.off 函数</h3><blockquote>
<p>用法：</p>
<div class="hljs"><pre><code class="hljs js">dom.on(test, <span class="hljs-string">&#x27;click&#x27;</span>, fn)  <span class="hljs-comment">// fn是函数，  添加了点击事件</span>
dom.off(test,<span class="hljs-string">&#x27;click&#x27;</span>,fn) <span class="hljs-comment">// 移除点击事件</span></code></pre></div>
</blockquote>
<blockquote>
<p>思路： 封装一下原生的DOM的addEventListener即可。</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">on(node, eventName, fn) &#123;
   node.addEventListener(eventName,fn)
 &#125;,
 off(node, eventName, fn) &#123; 
   node.removeEventListener(eventName,fn)
 &#125;</code></pre></div>



<p><strong>示例</strong></p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7ab7686a5a6a4ca6877f2aca3fc353de~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="示例1"></p>
<h2 id="查-（获取元素）"><a href="#查-（获取元素）" class="headerlink" title="查  （获取元素）"></a>查  （获取元素）</h2><ul>
<li><div class="hljs"><pre><code class="js">dom.find(&#39;选择器&#39;)  // 用于获取标签或标签们
<pre><code class="hljs crmsh">
- ```js
  dom.parent(<span class="hljs-keyword">node</span><span class="hljs-title">)  // 用于获取父元素</span></code></pre></div></code></pre>
</li>
<li><div class="hljs"><pre><code class="js">dom.children(node)  // 用于获取子元素
<pre><code class="hljs crmsh">
- ```js
  dom.siblings(<span class="hljs-keyword">node</span><span class="hljs-title">)  //用于获取兄弟姐妹元素</span></code></pre></div></code></pre>
</li>
<li><div class="hljs"><pre><code class="js">dom.next(node)  // 用于获取弟弟
<pre><code class="hljs crmsh">
- ```js
  dom.previous(<span class="hljs-keyword">node</span><span class="hljs-title">)  // 用于获取哥哥</span></code></pre></div></code></pre>
</li>
<li><div class="hljs"><pre><code class="js">dom.each(nodes,fn)  // 用于遍历所有节点
<pre><code class="hljs crmsh">
- ```js
  dom.index(<span class="hljs-keyword">node</span><span class="hljs-title">)  // 用于获取索引值为x</span> 的元素</code></pre></div>




</code></pre>
</li>
</ul>
<h3 id="dom-find-函数"><a href="#dom-find-函数" class="headerlink" title="dom.find 函数"></a>dom.find 函数</h3><blockquote>
<p>用法 和  document.querySelectorAll()  一致</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">find(selector,scope) &#123;
   <span class="hljs-keyword">return</span> (scope || <span class="hljs-built_in">document</span>).querySelectorAll(selector)
 &#125;</code></pre></div>



<p><strong>示例：</strong></p>
<p><img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/cfe498f0772a40a88159dc2fbdda663d~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="dom.find()示例"></p>
<p><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5a7e2cd3859b43bdadb32899d209fd54~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="dom.find()示例2"></p>
<h3 id="dom-parent-函数-和-dom-children-函数"><a href="#dom-parent-函数-和-dom-children-函数" class="headerlink" title="dom.parent  函数 和 dom.children 函数"></a>dom.parent  函数 和 dom.children 函数</h3><blockquote>
<p>用法: </p>
<div class="hljs"><pre><code class="hljs js">dom.parent(node)  <span class="hljs-comment">// 用于获取父元素</span>
dom.children(node)  <span class="hljs-comment">// 用于获取子元素</span></code></pre></div>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">parent(node) &#123;
   <span class="hljs-keyword">return</span> node.parentNode
 &#125;,
     
 children(node) &#123;
   <span class="hljs-keyword">return</span> node.children
  &#125;</code></pre></div>



<h3 id="dom-siblings-函数"><a href="#dom-siblings-函数" class="headerlink" title="dom.siblings 函数"></a>dom.siblings 函数</h3><blockquote>
<p>用法：</p>
<div class="hljs"><pre><code class="hljs js">dom.siblings(node)  <span class="hljs-comment">//用于获取兄弟姐妹元素 (除了自己)</span></code></pre></div>
</blockquote>
<blockquote>
<p>思路：  用 node.parentNode.children 获取所有子元素， 因为获取的伪数组， 转换为数组后过滤掉自己。</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">siblings(node) &#123;
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Array</span>.from(node.parentNode.children)
    .filter(<span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> n !== node)
&#125;,</code></pre></div>



<p><strong>dom.parent  、dom.children  、 dom.siblings  示例</strong></p>
<p><img src="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/1928c301d97e404ba905ef2ac1e54807~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="dom.parent  、dom.children  、 dom.siblings  示例"></p>
<h3 id="dom-next-函数-和-dom-previous-函数"><a href="#dom-next-函数-和-dom-previous-函数" class="headerlink" title="dom.next 函数  和 dom.previous 函数"></a>dom.next 函数  和 dom.previous 函数</h3><blockquote>
<p>用法：</p>
<div class="hljs"><pre><code class="hljs js">dom.next(node)  <span class="hljs-comment">// 用于获取下一个节点       （弟弟）节点</span>
dom.previous(node)   <span class="hljs-comment">// 用于获取上一个节点      （哥哥）节点</span></code></pre></div>
</blockquote>
<blockquote>
<p>思路： 我们使用 node.nextSibing 时 可以会返回 文本节点， 这时我们需要排除文本节点即可  (nodeType 为1是元素节点、为3 是文本节点)       、    dom.previous的思路也是一样的</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">next(node) &#123;
   <span class="hljs-keyword">let</span> x = node.nextSibling
   <span class="hljs-keyword">while</span> (x &amp;&amp; x.nodeType === <span class="hljs-number">3</span>) &#123; <span class="hljs-comment">//  1是元素节点， 3是文本节点</span>
     x = x.nextSibling
   &#125;
   <span class="hljs-keyword">return</span> x
 &#125;,
 previous(node) &#123;
   <span class="hljs-keyword">let</span> x = node.previousSibling
   <span class="hljs-keyword">while</span> (x &amp;&amp; x.nodeType === <span class="hljs-number">3</span>) &#123; <span class="hljs-comment">//  1是元素节点， 3是文本节点</span>
     x = x.previousSibling
   &#125;
   <span class="hljs-keyword">return</span> x
 &#125;</code></pre></div>





<p><strong>示例</strong></p>
<p><img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ff9f33b4913f4ddaa9aeabd6fb12736e~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="dom.next示例"></p>
<p><img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c8b6507260124bbe84d8b542eaa30ef9~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="dom.previous示例"></p>
<h3 id="dom-each-函数"><a href="#dom-each-函数" class="headerlink" title="dom.each 函数"></a>dom.each 函数</h3><blockquote>
<p>用法： 遍历每个元素，使他做对应的事</p>
<div class="hljs"><pre><code class="hljs js">dom.each(nodes,fn)  <span class="hljs-comment">// 用于遍历所有节点</span></code></pre></div>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">each(nodeList, fn) &#123;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; nodeList.length; i++) &#123;
    fn.call(<span class="hljs-literal">null</span>, nodeList[i])
  &#125;
&#125;</code></pre></div>



<p><strong>示例：</strong></p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/308ff6e8cb4c4594a33b6dc8919ed0ac~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="dom.each"></p>
<h3 id="dom-index-函数"><a href="#dom-index-函数" class="headerlink" title="dom.index 函数"></a>dom.index 函数</h3><blockquote>
<p>用法： 返当前节点在父节点内的索引值</p>
<div class="hljs"><pre><code class="hljs js">dom.index(node)  <span class="hljs-comment">// 返回当前节点在它父节点中的索引值</span></code></pre></div>
</blockquote>
<blockquote>
<p>思路： 获取自己的父节点的所有子节点, 然后遍历， 如果遍历的子节点是自己，就返回 i</p>
</blockquote>
<p><strong>源代码</strong></p>
<div class="hljs"><pre><code class="hljs js">index(node) &#123;
  <span class="hljs-keyword">const</span> list = dom.children(node.parentNode)
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; list.length; i++) &#123;
    <span class="hljs-keyword">if</span> (list[i] === node) &#123;
      <span class="hljs-keyword">return</span> i
    &#125;
  &#125;
&#125;</code></pre></div>



<p><strong>示例：</strong></p>
<p><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/550cdf330dc04fd8bdcd1b0e6edfd958~tplv-k3u1fbpfcp-watermark.image" srcset="/img/loading.gif" alt="dom.index "></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                <div class="post-meta mr-3">
                  <i class="iconfont icon-category"></i>
                  
                  <a class="hover-with-bg" href="/categories/JavaScript/">JavaScript</a>
                  
                </div>
                
                
                <div class="post-meta">
                  <i class="iconfont icon-tags"></i>
                  
                  <a class="hover-with-bg" href="/tags/JavaScript/">JavaScript</a>
                  
                </div>
                
              </div>
              
              
              <div class="post-prevnext row">
                <article class="post-prev col-6">
                  
                  
                  <a href="/2020/12/09/30-%E4%BB%A5jQuery%E7%9A%84%E8%AE%BE%E8%AE%A1%E6%80%9D%E6%83%B3%E5%B0%81%E8%A3%85DOM/">
                    <i class="iconfont icon-arrowleft"></i>
                    <span class="hidden-mobile">以jQuery的设计思想封装DOM(总结)</span>
                    <span class="visible-mobile">上一篇</span>
                  </a>
                  
                </article>
                <article class="post-next col-6">
                  
                  
                  <a href="/2020/11/28/28-%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript/">
                    <span class="hidden-mobile">你不知道的JavaScript</span>
                    <span class="visible-mobile">下一篇</span>
                    <i class="iconfont icon-arrowright"></i>
                  </a>
                  
                </article>
              </div>
              
            </div>

            
            <!-- Comments -->
            <article class="comments" id="comments">
              
              
  <div id="vcomments"></div>
  <script type="text/javascript">
    function loadValine() {
      addScript('https://cdn.staticfile.org/valine/1.4.14/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "hjxsDRXYScicliqD8I8JqoTu-gzGzoHsz",
          app_key: "qUcAEReEqeEVp5wwXJ41uCCp",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: true,
          recordIP: false,
          serverURLs: "",
        });
      });
    }
    waitElementVisible('vcomments', loadValine);
  </script>
  <noscript>Please enable JavaScript to view the <a target="_blank" href="https://valine.js.org" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


            </article>
            
          </article>
        </div>
      </div>
    </div>
    
    <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
      <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

    </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    
      <script  src="/js/lazyload.js" ></script>
    
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "手写DOM&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "always",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  











  

  

  

  

  

  





</body>
</html>
